const errorTypes = require('../constants/error-types');
const {getUserByPhone,getUserByName} = require('../service/user_service');
const md5password = require('../utils/password-handle');

const verifyUser = async (ctx, next) => {
  // 1.获取用户名和密码
  try {
    const { phone, password, username } = ctx.request.body;

    // 2.判断用户名或者密码不能空
    if (!phone || !password||!username) {
      const error = new Error(errorTypes.USERNAME_OR_PHONE_OR_PASSWORD_IS_REQUIRED);
      return ctx.app.emit('error', error, ctx);
    }
  
    // // 3.判断这次注册的用户名是没有被注册过
    const result = await getUserByName(username);
    if (result.length) {
      const error = new Error(errorTypes.USER_ALREADY_EXISTS);
      return ctx.app.emit('error', error, ctx);
    }
    let res = await getUserByPhone(phone);
    if (res.length) {
      const error = new Error(errorTypes.PHONE_ALREADY_REGISTERED);
      return ctx.app.emit('error', error, ctx);
    }
    
  
    await next();
  } catch (error) {
    console.log(error)
  }
 
}

const handlePassword = async (ctx, next) => {
  const { password } = ctx.request.body;
  ctx.request.body.password = md5password(password)

  await next();
}

module.exports = {
  verifyUser,
  handlePassword
}
